package mspbots.autotask.data.core.productnotes;

import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.autotask.common.ResultMsg;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Log4j2
@Component
@RequiredArgsConstructor
public class ProductNotesReceiver {

    private final ProductNotesRepository productnotesRepository;

//    @RabbitListener(queues = "auto-task.product-notes.sync")
    public void syncTask(ResultMsg content) {

        ProductNote productnote = ProductNote.builder().otherId(content.getId())
                .tenantId(content.getTenantId()).syncTime(content.getSyncDate())
                .createdTime(LocalDateTime.parse(content.getEntity().get("createDateTime").textValue(),
                        DateTimeFormatter.ISO_OFFSET_DATE_TIME))
                .updatedTime(LocalDateTime.parse(content.getEntity().get("lastActivityDate").textValue(),
                        DateTimeFormatter.ISO_OFFSET_DATE_TIME))
                .entity(content.getEntity())
                .build();

        if (ObjectUtils.isEmpty(productnote.getOtherId())){
            return;
        }

        this.productnotesRepository.findByOtherIdAndTenantId(content.getId(), content.getTenantId())
                .map(ticket -> {
                    productnote.setId(ticket.getId());
                    return productnote;

                })
                .defaultIfEmpty(productnote)
                .flatMap(this.productnotesRepository::save)
                .block();
    }
}
